package com.cscp.javastudy.basic.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过反射创建对象
 */
public class CreateObject {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        Class c1 = Class.forName("com.cscp.javastudy.basic.reflect.User");
        // 通过反射创建一个对象
        User user = (User)c1.newInstance();
        // 通过构造器创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = (User)constructor.newInstance("Jama", 11, 22);
        System.out.println(user2);
        // 通过反射调用方法
        User user3 = (User) c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user3,"whoisjama");
        System.out.println(user3.getName());
        // 通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true); //私有属性需要设置访问权限
        name.set(user4, "whoisjama2");
        System.out.println(user4.getName());

    }
}
